package com.jams.auth.security;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.jams.auth.entity.JamsAuthUser;
import com.jams.common.core.constant.CommonConstant;
import com.jams.common.core.constant.SecurityConstants;
import com.jams.common.core.system.JamsResponse;
import com.jams.rbac.api.dto.UserInfo;
import com.jams.rbac.api.entity.User;
import com.jams.rbac.api.feign.RemoteUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service
public class JamsUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private  RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList();

        JamsResponse<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
        UserDetails userDetails = getUserDetails(result);
        return userDetails;
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(JamsResponse<UserInfo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo info = result.getData();
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        User user = info.getUser();
        boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstant.STATUS_NORMAL);
        // 构造security用户
        return new JamsAuthUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT +user.getPassword(),
                enabled, true, true, !CommonConstant.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }

    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("123456");
        System.out.println(encode);
    }
}
